/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bea.banana;

import java.util.Random;

/**
 *
 * @author user1
 */
public class BananaKey {
    
    public static byte[] kunci;
    
    
    public void inputKey(byte[] input){
        Random r = new Random();
        if (input.length < 8){
            kunci = new byte[8];
            System.arraycopy(input, 0, kunci, 0, input.length);
            for (int i=0 ; i < 8 - input.length; i++){
                r.setSeed((long) kunci[i]);
                kunci[input.length + i] = (byte) (r.nextInt(128));
            }
        }else{
            kunci = input;            
        }       
    
        long seed = (long) (((BananaEngine.unsignedByteToInt(kunci[3])) * (BananaEngine.unsignedByteToInt(kunci[7]))) *(BananaEngine.unsignedByteToInt(kunci[0])) *(BananaEngine.unsignedByteToInt(kunci[5])) + (BananaEngine.unsignedByteToInt(kunci[1])) + (BananaEngine.unsignedByteToInt(kunci[2])) + (BananaEngine.unsignedByteToInt(kunci[4])) + (BananaEngine.unsignedByteToInt(kunci[6])));
        r.setSeed(seed);
        byte[] newkey = new byte[8];
        for (int x =0; x<63; x++){
            
            setBit(newkey,x,getBit(kunci, r.nextInt(64)));
            
        }
        
        System.arraycopy(newkey, 0, kunci, 0, 8);
    }
    
    
    private int getBit(byte[] data, int pos) {
        int posByte = pos / 8;
        int posBit = pos % 8;
        byte valByte = data[posByte];
        int valInt = valByte >> (8 - (posBit + 1)) & 0x0001;
        return valInt;
    }

    private void setBit(byte[] data, int pos, int val) {
        int posByte = pos / 8;
        int posBit = pos % 8;
        byte oldByte = data[posByte];
        oldByte = (byte) (((0xFF7F >> posBit) & oldByte) & 0x00FF);
        byte newByte = (byte) ((val << (8 - (posBit + 1))) | oldByte);
        data[posByte] = newByte;
    }
    
    
    public byte[] genKeyFeistel(int i){
        
        byte[] b = new byte[4];
        
        i = i%8;
        b[0] = kunci[i];
        b[1] = (byte) (b[0] + (52));
        b[2] = (byte) (b[1] + (80));
        b[3] = (byte) (b[2] + (17));       
        
        return b;
    }
    
    
}
